import { useState, useRef, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { BottomNavigation } from "@/components/ui/bottom-navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  ArrowLeft,
  Edit3,
  Check,
  X,
  MapPin,
  Clock,
  Calendar,
  Share,
  Download,
  Heart,
  MoreHorizontal,
} from "lucide-react";

// Mock photo data - in real app this would come from props/API
const generateEventPhotos = (count: number, baseThumbnail: string) => {
  const photoUrls = [
    "https://images.pexels.com/photos/9373300/pexels-photo-9373300.jpeg",
    "https://images.pexels.com/photos/5504722/pexels-photo-5504722.jpeg",
    "https://images.pexels.com/photos/4241550/pexels-photo-4241550.jpeg",
    "https://images.pexels.com/photos/2614816/pexels-photo-2614816.jpeg",
    "https://images.pexels.com/photos/30629862/pexels-photo-30629862.jpeg",
    "https://images.pexels.com/photos/5220043/pexels-photo-5220043.jpeg",
    "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
    "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
    "https://images.pexels.com/photos/3222196/pexels-photo-3222196.jpeg",
    "https://images.pexels.com/photos/7993600/pexels-photo-7993600.jpeg",
  ];

  return Array.from({ length: count }, (_, index) => ({
    id: index + 1,
    url: index === 0 ? baseThumbnail : photoUrls[index % photoUrls.length],
    alt: `Photo ${index + 1}`,
    favorite: Math.random() > 0.8, // Random favorites
  }));
};

// Mock event data - this would come from props/routing/API
const mockEventData = {
  breakfast: {
    id: "breakfast",
    title: "早餐",
    time: "08:00",
    date: "2024-01-15",
    location: "酒店",
    photos: 5,
    thumbnail:
      "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
    isAIGenerated: true,
  },
  "forbidden-city": {
    id: "forbidden-city",
    title: "故宫博物院",
    time: "09:00",
    date: "2024-01-15",
    location: "北京",
    photos: 25,
    thumbnail:
      "https://images.pexels.com/photos/9373300/pexels-photo-9373300.jpeg",
    isAIGenerated: true,
  },
  "hall-of-supreme-harmony": {
    id: "hall-of-supreme-harmony",
    title: "太和殿",
    time: "11:30",
    date: "2024-01-15",
    location: "故宫",
    photos: 12,
    thumbnail:
      "https://images.pexels.com/photos/5504722/pexels-photo-5504722.jpeg",
    isAIGenerated: true,
  },
  "imperial-garden": {
    id: "imperial-garden",
    title: "御花园",
    time: "12:30",
    date: "2024-01-15",
    location: "故宫",
    photos: 18,
    thumbnail:
      "https://images.pexels.com/photos/4241550/pexels-photo-4241550.jpeg",
    isAIGenerated: true,
  },
  "lunch-time": {
    id: "lunch-time",
    title: "午餐时光",
    time: "14:30",
    date: "2024-01-15",
    location: "王府井",
    photos: 8,
    thumbnail:
      "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
    isAIGenerated: true,
  },
  "wangfujing-street": {
    id: "wangfujing-street",
    title: "王府井大街",
    time: "16:00",
    date: "2024-01-15",
    location: "王府井",
    photos: 15,
    thumbnail:
      "https://images.pexels.com/photos/2614816/pexels-photo-2614816.jpeg",
    isAIGenerated: true,
  },
  "snack-street": {
    id: "snack-street",
    title: "小吃街",
    time: "17:30",
    date: "2024-01-15",
    location: "王府井",
    photos: 22,
    thumbnail:
      "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
    isAIGenerated: true,
  },
  dinner: {
    id: "dinner",
    title: "晚餐",
    time: "19:00",
    date: "2024-01-15",
    location: "烤鸭店",
    photos: 11,
    thumbnail:
      "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
    isAIGenerated: true,
  },
  "night-photography": {
    id: "night-photography",
    title: "夜景拍摄",
    time: "20:30",
    date: "2024-01-15",
    location: "天安门",
    photos: 28,
    thumbnail:
      "https://images.pexels.com/photos/3222196/pexels-photo-3222196.jpeg",
    isAIGenerated: true,
  },
  "night-market": {
    id: "night-market",
    title: "夜市逛街",
    time: "21:45",
    date: "2024-01-15",
    location: "前门",
    photos: 16,
    thumbnail:
      "https://images.pexels.com/photos/7993600/pexels-photo-7993600.jpeg",
    isAIGenerated: true,
  },
  "bar-rest": {
    id: "bar-rest",
    title: "酒吧小憩",
    time: "22:30",
    date: "2024-01-15",
    location: "三里屯",
    photos: 7,
    thumbnail:
      "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
    isAIGenerated: true,
  },
};

export default function PhotoEvent() {
  const navigate = useNavigate();
  const { eventId } = useParams();
  const [isEditing, setIsEditing] = useState(false);
  const [eventTitle, setEventTitle] = useState("");
  const [selectedPhoto, setSelectedPhoto] = useState<number | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Get event data
  const eventData = mockEventData[eventId as keyof typeof mockEventData];
  const photos = eventData
    ? generateEventPhotos(eventData.photos, eventData.thumbnail)
    : [];

  useEffect(() => {
    if (eventData) {
      setEventTitle(eventData.title);
    }
  }, [eventData]);

  useEffect(() => {
    if (isEditing && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [isEditing]);

  if (!eventData) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-xl font-semibold text-foreground mb-2">
            Event not found
          </h1>
          <Button onClick={() => navigate("/timeline")}>返回时间轴</Button>
        </div>
      </div>
    );
  }

  const handleSaveTitle = () => {
    setIsEditing(false);
    // Here you would save to API
    console.log("Saving title:", eventTitle);
  };

  const handleCancelEdit = () => {
    setEventTitle(eventData.title);
    setIsEditing(false);
  };

  return (
    <div className="min-h-screen bg-background pb-20">
      {/* Header */}
      <header className="sticky top-0 z-40 bg-background/80 backdrop-blur-lg border-b border-border">
        <div className="flex items-center justify-between p-4">
          <div className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => navigate("/timeline")}
            >
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <div>
              <div className="flex items-center gap-2">
                {isEditing ? (
                  <div className="flex items-center gap-2">
                    <input
                      ref={inputRef}
                      value={eventTitle}
                      onChange={(e) => setEventTitle(e.target.value)}
                      className="text-xl font-semibold bg-transparent border-b border-primary focus:outline-none"
                      onKeyDown={(e) => {
                        if (e.key === "Enter") handleSaveTitle();
                        if (e.key === "Escape") handleCancelEdit();
                      }}
                    />
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleSaveTitle}
                      className="h-6 w-6"
                    >
                      <Check className="h-4 w-4 text-green-600" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={handleCancelEdit}
                      className="h-6 w-6"
                    >
                      <X className="h-4 w-4 text-red-600" />
                    </Button>
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    <h1 className="text-xl font-semibold text-foreground">
                      {eventTitle}
                    </h1>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => setIsEditing(true)}
                      className="h-6 w-6"
                    >
                      <Edit3 className="h-4 w-4" />
                    </Button>
                  </div>
                )}
              </div>
              {eventData.isAIGenerated && !isEditing && (
                <p className="text-xs text-muted-foreground">AI 生成的标题</p>
              )}
            </div>
          </div>
          <Button variant="ghost" size="icon">
            <MoreHorizontal className="h-5 w-5" />
          </Button>
        </div>
      </header>

      {/* Event Info */}
      <div className="p-4 border-b border-border bg-muted/20">
        <div className="flex items-center gap-4 text-sm text-muted-foreground">
          <div className="flex items-center gap-1">
            <Calendar className="h-4 w-4" />
            {eventData.date}
          </div>
          <div className="flex items-center gap-1">
            <Clock className="h-4 w-4" />
            {eventData.time}
          </div>
          <div className="flex items-center gap-1">
            <MapPin className="h-4 w-4" />
            {eventData.location}
          </div>
        </div>
        <p className="text-sm text-muted-foreground mt-2">
          {photos.length} 张照片
        </p>
      </div>

      {/* Action Bar */}
      <div className="p-4 border-b border-border">
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm">
            <Share className="h-4 w-4 mr-2" />
            分享
          </Button>
          <Button variant="outline" size="sm">
            <Download className="h-4 w-4 mr-2" />
            下载
          </Button>
          <Button variant="outline" size="sm">
            <Heart className="h-4 w-4 mr-2" />
            收藏
          </Button>
        </div>
      </div>

      {/* Photo Grid */}
      <div className="p-4">
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
          {photos.map((photo) => (
            <Card
              key={photo.id}
              className="overflow-hidden cursor-pointer hover:shadow-lg transition-shadow"
              onClick={() => setSelectedPhoto(photo.id)}
            >
              <div className="relative aspect-square">
                <img
                  src={photo.url}
                  alt={photo.alt}
                  className="w-full h-full object-cover"
                />
                {photo.favorite && (
                  <div className="absolute top-2 right-2">
                    <Heart className="h-4 w-4 text-red-500 fill-red-500" />
                  </div>
                )}
                {selectedPhoto === photo.id && (
                  <div className="absolute inset-0 bg-primary/20 border-2 border-primary rounded-lg" />
                )}
              </div>
            </Card>
          ))}
        </div>
      </div>

      {/* Photo Selection Actions */}
      {selectedPhoto && (
        <div className="fixed bottom-24 left-4 right-4 bg-background/90 backdrop-blur-lg border border-border rounded-lg p-3">
          <div className="flex items-center justify-between">
            <p className="text-sm text-muted-foreground">已选择 1 张照片</p>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm">
                删除
              </Button>
              <Button variant="outline" size="sm">
                分享
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setSelectedPhoto(null)}
              >
                取消
              </Button>
            </div>
          </div>
        </div>
      )}

      <BottomNavigation />
    </div>
  );
}
